package top.milkbox.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;
import top.milkbox.domain.Post;
import top.milkbox.domain.PostComment;
import top.milkbox.domain.User;
import top.milkbox.info.PostImage;
import top.milkbox.service.PostService;
import top.milkbox.mapper.PostMapper;
import org.springframework.stereotype.Service;
import top.milkbox.service.UserService;
import top.milkbox.utils.GuoUtilsDate;
import top.milkbox.utils.GuoUtilsLog;
import top.milkbox.utils.GuoUtilsRandom;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author xiaoguo
 * @description 针对表【tb_post】的数据库操作Service实现
 * @createDate 2022-10-23 16:55:21
 */
@Service
public class PostServiceImpl extends ServiceImpl<PostMapper, Post>
        implements PostService {

    @Autowired
    private UserService userService;

    @Autowired
    private PostMapper postMapper;

    @Autowired
    private PostImage postImage;

    /**
     * 保存一条帖子
     *
     * @param token    用户设备的token
     * @param fileList 图片数组
     * @param content  帖子内容
     * @return 保存成功返回true
     */
    @Override
    public Boolean savePost(String token, MultipartFile[] fileList, String content) {
        log.debug("准备保存帖子...");
        // 只要通过了拦截器，这里就不会为空
        Integer userId = userService.getUserFromRedis(token).getUserId();

        // 先将帖子的内容存入数据库，并获取到这一条数据的id
        Post post = new Post();
        post.setUserId(userId);
        post.setContent(content);
        post.setTime(GuoUtilsDate.getDateNow());
        if (postMapper.insert(post) != 1) {
            log.error("postContent保存数据库失败");
            return false;
        }


        if (fileList != null && fileList.length > 0) {
            // 要插入到数据库的image字段
            StringBuilder image = new StringBuilder();

            for (int i = 0; i < fileList.length; i++) {
                log.debug("正在处理图片(" + (i + 1) + "/" + fileList.length + ")...");
                String contentType = fileList[i].getContentType();
                // 判断是否为图片类型，这里不会发生空指针异常，因为在controller中空值是传不进来的会被异常捕获
                if (!"image".equals(contentType.split("/")[0])) {
                    log.error("当前图片类型不支持：" + contentType);
                    continue;
                }

                String fileExtension = "." + contentType.split("/")[1];
                // 生成新的文件名
                String newFileName = "postImage_" + post.getId() +
                        "_" + new Date().getTime() + "_" +
                        GuoUtilsRandom.getRandomString(4) + fileExtension;
                // 生成磁盘位置路径
                String newDiskAddress = postImage.getDiskAddress() + newFileName;
                log.debug("新生成的文件磁盘地址：" + newDiskAddress);

                try {
                    // 将当前图片保存到磁盘中
                    fileList[i].transferTo(new File(newDiskAddress));
                } catch (IOException e) {
                    log.error("当前图片保存失败，请检查图片保存的路径");
                    throw new RuntimeException(e);
                }
                // 拼接image字段
                if (image.length() == 0) {
                    image.append(newFileName);
                } else {
                    image.append(postImage.getImageSplit()).append(newFileName);
                }
            }
            log.debug("所有图片处理完毕，生成image字段：" + image);
            post.setImage(image.toString());
            log.debug("正在存入数据：" + post);
            // 数据库操作
            boolean isSuccess = postMapper.updateById(post) == 1;
            log.debug("保存结果：" + isSuccess);
            return isSuccess;
        } else {
            log.debug("用户没有选择图片，无图片方式保存成功：" + post);
            return true;
        }

    }

    /**
     * 分页查询
     */
    @Override
    public PageInfo<Post> selectPage(
            String token, Integer pageNum, Integer pageSize, Integer isCollectionLimit
    ) {
        pageNum = pageNum == null ? 1 : pageNum;
        pageSize = pageSize == null ? 3 : pageSize;
        try {
            PageHelper.startPage(pageNum, pageSize);
            // 获取userID
            User user = userService.getUserFromRedis(token);
            List<Post> postList = null;
            if (user != null) {
                postList = postMapper.selectAll(user.getUserId(), isCollectionLimit);
            } else {
                postList = postMapper.selectAll(null, null);
            }

            if (postList == null) {
                log.warn("没有帖子数据，或查询出现异常");
                return null;
            }
            for (Post post : postList) {
                // 预处理发帖用户
                userService.preprocessingUser(post.getUser());

                // 预处理post信息
                preprocessingPost(post);
            }
            log.debug("第" + pageNum + "页，每页" + pageSize + "条，查询结束，" +
                    "操作的用户为：" + (user == null ? "游客身份" : user.getUserId()));
            return new PageInfo<>(postList);
        } finally {
            PageHelper.clearPage();
        }
    }

    /**
     * 通过postId查询这一条帖子的所有详细的信息
     *
     * @param postId 帖子的id
     * @return 返回post全部数据
     */
    @Override
    public Post selectOneAll(String token, Integer postId) {
        // 获取userID
        User user = userService.getUserFromRedis(token);
        Post post = null;
        if (user != null) {
            post = postMapper.selectOneAll(user.getUserId(), postId);
        } else {
            post = postMapper.selectOneAll(null, postId);
        }
        if (post == null) {
            log.debug("没有此帖子，帖子id：" + postId);
            return null;
        }
        // 当前帖子浏览量加一
        postMapper.viewGrowth(postId);
        // 预处理用户信息
        userService.preprocessingUser(post.getUser());
        // 预处理post信息
        preprocessingPost(post);
        // 预处理评论中的用户信息
        List<PostComment> postCommentList = post.getPostCommentList();
        if (postCommentList != null && postCommentList.size() > 0) {
            for (PostComment postComment : postCommentList) {
                userService.preprocessingUser(postComment.getUser());
            }
        }

        log.debug(GuoUtilsLog.lengthLimit(post.toString()));
        return post;
    }


    @Override
    public void preprocessingPost(Post post) {
        if (post.getImage() != null) {
            // 将图片转为集合
            String[] imageArray = post.getImage().split(postImage.getImageSplit());
            // 拼接图片URL
            for (int i = 0; i < imageArray.length; i++) {
                imageArray[i] = postImage.getCommonAddress() + imageArray[i];
            }
            // 设置帖子图片URL列表
            post.setImageList(Arrays.asList(imageArray));
        }
    }
}




